<template>
  <a-modal
    :title="title"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-show="isAdd" label="店铺所有人" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            showSearch
            :defaultActiveFirstOption="false"
            :showArrow="false"
            :filterOption="false"
            placeholder="店铺所有人"
            @search="getSellerSearch"
            @change="getSellerListChange"
            notFoundContent="null"
            v-decorator="['sellerId', validatorRules.sellerId]"
          >
            <a-select-option v-for="d in sellerList" :key="d.id">{{ d.mobile }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="店铺名称">
          <a-input placeholder="请输入店铺名称" v-decorator="['shopName', validatorRules.shopName]" />
        </a-form-item>
        <a-form-item label="店铺logo图" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            action="/mall-serve/v1/sys/common/uploadImage"
            name="file"
            listType="picture-card"
            :fileList="logoList"
            @preview="handleLogoPreview"
            @change="handleLogoChange"
          >
            <div v-if="logoList.length < 1">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleLogoCancel">
            <img alt="example" :src="previewImage" />
          </a-modal>
          <!-- <a-modal :visible="false" :footer="null" @cancel="handleLogoCancel">
                <div v-for="(fileDetail,index) in logoList" :key="index">
                  <div style="float: left;width:104px;height:104px;margin-right: 10px;margin: 0 8px 8px 0;">
                    <div
                      style="width: 100%;height: 100%;position: relative;padding: 8px;border: 1px solid #d9d9d9;border-radius: 4px;">
                      <img style="width: 100%;" :src="imageDownloadUri+fileDetail"  :preview="false">
                    </div>
                  </div>
                </div>
          </a-modal> -->
        </a-form-item>
        <a-form-item label="店铺照片" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-upload
            action="/mall-serve/v1/sys/common/uploadImage"
            name="file"
            listType="picture-card"
            @preview="handlePicPreview"
            @change="handlePicChange"
            :fileList="picList"
            class="avatar-uploader"
            :showUploadList="true"
          >
            <div v-if="picList.length < 3">
              <a-icon type="plus" />
              <div class="ant-upload-text">上传</div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handlePicCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-item>
        <a-form-item label="店铺类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-select
            showSearch
            :defaultActiveFirstOption="false"
            :showArrow="false"
            :filterOption="false"
            placeholder="指定店铺类型"
            @search="getShopTypeSearch"
            @click="getShopTypeChange"
            notFoundContent="null"
            v-decorator="['shopType', { rules: [{ required: true, message: '请指定店铺类型' }] }]"
          >
            <a-select-opt-group v-for="item in shopTypeList" :key="item.id">
              <span slot="label">
                <a-icon type="user" />
                {{ item.name }}
              </span>
              <a-select-option :key="n.id" v-for="n in item.children">{{ n.name }}</a-select-option>
            </a-select-opt-group>
          </a-select>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="店铺简介">
          <a-input placeholder="请输入店铺简介" v-decorator="['brief', validatorRules.brief]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="联系人手机号">
          <a-input placeholder="请输入联系人手机号" v-decorator="['linkmanMobile', validatorRules.linkmanMobile]" />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="商品类型">
          <a-select
            style="min-width:200px"
            mode="multiple"
            v-decorator="['goodsTyeList', validatorRules.goodsTyeList]"
            :defaultActiveFirstOption="false"
            :showArrow="false"
            :filterOption="false"
            placeholder="指定商品类型"
            @change="getGoodTypeChange"
            notFoundContent="null"
          >
            <a-select-option :key="n.id" v-for="n in goodTypeList">{{ n.name }}</a-select-option>
          </a-select>
          <!-- <a-input placeholder="请输入联系人手机号" v-decorator="['linkmanMobile', validatorRules.linkmanMobile]" /> -->
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="核销方式">
          <a-radio-group v-decorator="['workType', validatorRules.workType]">
            <a-radio-button value="1">到店核销</a-radio-button>
            <a-radio-button value="2">上门核销</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="分成类型">
          <a-radio-group v-decorator="['divideType', validatorRules.divideType]" @change="handlerDivideType">
            <a-radio-button value="1">按比例分成</a-radio-button>
            <a-radio-button value="2">按次数分成</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="请输入店铺分成比例"
          v-show="requiredDivideNum"
        >
          <a-input placeholder="请输入店铺分成比例" v-decorator="['divideNum', validatorRules.divideNum]" />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="店铺订单每次分成数"
          v-show="!requiredDivideNum"
        >
          <a-input placeholder="请输入店铺订单每次分成数" v-decorator="['divideNum', validatorRules.divideNum2]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="店铺地址">
          <a-input placeholder="请输入店铺地址" v-decorator="['shopAddress', validatorRules.shopAddress, {}]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="详细地址">
          <a-input placeholder="请输入详细地址" v-decorator="['addressDetail', validatorRules.addressDetail, {}]" />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="坐标">
          <a-input-search
            placeholder="请搜索坐标"
            :disable="false"
            v-decorator="['coordinate', {}]"
            @search="searchByStationName()"
            id="lngslats"
            size="large"
          >
            <a-button slot="enterButton">搜索</a-button>
          </a-input-search>
          <!-- <a-input placeholder="" v-decorator="['coordinate', {}]" />
          <a-input type="button" value="查询" v-on:click="searchByStationName();" />-->
        </a-form-item>
      </a-form>
    </a-spin>
    <div id="div">
      <div id="container">
        <a-modal title="Title" :visible="modalVisible" @ok="handleModalOk" @cancel="handleModalCancel">
          <p>{{ modalText }}</p>
        </a-modal>
      </div>
    </div>
  </a-modal>
</template>
<script>
import imgzip from 'imgzip'
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from 'moment'
import { validatePhone, validateTelphone, validateIdNo, validateEMail, validateQQ } from '@/utils/validator'
import { type } from 'os'
export default {
  name: 'ShopModal',
  data() {
    return {
      selectedGoodType: [],
      goodTypeList: [],
      modalVisible: false,
      modalText: '',
      previewVisible: false,
      requiredDivideNum: true,
      imageDownloadUri: '/mall-serve/v1/sys/common/getImageByUri?imageUri=',
      selectSellerShow: true,
      previewImage: '',
      previewPicImage: '',
      previewPicVisible: false,
      isEdit: false,
      isAdd: true,
      logoList: [],
      logoName: '',
      picList: [],
      latitude: [],
      longitude: [],
      location: [lng => '', lat => ''],
      val: '',
      title: '操作',
      visible: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      typeList: [],
      sellerList: [],
      shopTypeList: [],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        goodsTyeList: {
          rules: [{ required: true, message: '请选择商户' }]
        },
        brief: {
          rules: [{ required: true, message: '请选择商户' }]
        },
        linkmanMobile: {
          rules: [{ required: true, message: '请选择商户' }]
        },
        sellerId: {
          rules: [{ required: this.isEdit, message: '请选择商户' }]
        },
        // goodsTypeList: {
        //   rules: [
        //     { required: true, message: '请选择商铺可以添加的商品类型' }
        //   ]
        // },
        shopName: {
          rules: [
            { required: true, message: '请输入商铺名称' },
            { max: 30, message: '商铺名称最多支持30个字符' }
          ]
        },
        divideType: {
          rules: [
            { required: true, message: '请输入选择分成类型' },
            { max: 30, message: '商铺名称最多支持30个字符' }
          ],
          initialValue: '1'
        },
        workType: {
          rules: [
            { required: true, message: '请输入分成比例' },
            { max: 30, message: '商铺名称最多支持30个字符' }
          ],
          initialValue: '1'
        },
        divideNum: {
          rules: [
            { required: this.requiredDivideNum, message: '请输入分成比例' },
            { max: 30, message: '商铺名称最多支持30个字符' }
          ],
          initialValue: '0'
        },
        divideNum2: {
          rules: [
            { required: !this.requiredDivideNum, message: '请输入分成比例' },
            { max: 30, message: '商铺名称最多支持30个字符' }
          ],
          initialValue: '0'
        },
        mobile: {
          rules: [
            { required: true, message: '请输入手机号' },
            { validator: validatePhone, trigger: blur }
          ]
        },
        shopAddress: {
          rules: [
            { required: true, message: '请输入店铺地址' },
            { max: 50, message: '商铺地址最多支持50个字符' }
          ]
        },
        addressDetail: {
          rules: [
            { required: true, message: '请输入详细地址' },
            { max: 100, message: '商铺详细地址最多支持100个字符' }
          ]
        },
        idCard: {
          rules: [
            { required: true, message: '请输入身份证号' },
            { validator: validateIdNo, trigger: blur }
          ]
        }
      },
      url: {
        add: '/shop/web/add',
        edit: '/shop/web/edit'
      }
    }
  },
  created() {
    this.getGoodsTypeListByShopId()
  },
  mounted() {},
  activated() {
    this.selectedGoodType = []
    this.goodTypeList = []
    this.getGoodsTypeListByShopId()
  },
  methods: {
    //获取商铺可添加的商品类型
    getGoodsTypeListByShopId() {
      getAction('/shopType/getGoodsTypeListOfFirstLevel')
        .then(res => {
          if (res.success) {
            this.goodTypeList = res.result
          }
        })
        .catch(err => {})
    },
    getGoodTypeChange(value) {
      this.selectedGoodType = value
    },
    searchByStationName: function() {
      let that = this
      var map = new BMap.Map('container', {
        enableMapClick: true
      }) // 创建Map实例
      map.clearOverlays() //清空原来的标注
      var localSearch = new BMap.LocalSearch(map)
      localSearch.enableAutoViewport() //允许自动调节窗体大小
      var keyword = this.form.getFieldValue('addressDetail')
      localSearch.setSearchCompleteCallback(function(searchResult) {
        var poi = searchResult.getPoi(0)
        map.centerAndZoom(poi.point, 13)
        var marker = new BMap.Marker(new BMap.Point(poi.point.lng, poi.point.lat)) // 创建标注，为要查询的地方对应的经纬度
        map.addOverlay(marker)
        that.form.setFieldsValue({ coordinate:poi.point.lat+',' +poi.point.lng   })
        marker.addEventListener('click', function() {
          this.openInfoWindow(infoWindow)
        })
        marker.setAnimation(BMAP_ANIMATION_BOUNCE) //跳动的动画
      })
      localSearch.search(keyword)
    },
    handlerDivideType(value) {
      this.requiredDivideNum = !this.requiredDivideNum
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e
      }
      // return e && e.fileList
      return e && [e.file] // 如果单单一个upload组件，不在form表单里，则直接beforeUpload方法里this.fileList = [file]则会实现替换文件，只显示一条记录的动态效果，但form表单里需要在这个方法里设置
    },
    getSellerListChange(value) {},
    getSellerSearch(value) {
      if (value.length > 3) {
        let params = { mobile: value + '*' }
        getAction('/seller/web/list', params).then(res => {
          if (res.success) {
            this.sellerList = res.result.records
          }
          if (res.code === 500) {
            this.$message.warning(res.message)
          }
        })
      }
    },
    getShopTypeChange() {
      getAction('/shopType/getShopTypeList').then(res => {
        if (res.success) {
          this.shopTypeList = res.result
        }
        if (res.code === 500) {
          this.$message.warning(res.message)
        }
      })
    },

    getShopTypeSearch(value) {},
    hanlerPhoto(file) {
      imgzip.photoCompress(file, {}, function(base64) {
        //转blod流上传
        let blod = imgzip.convertBase64UrlToBlob(base64)
        return new Promise(function(resolve, reject) {
          resolve(blod)
        })
      })
    },
    initUploadParams() {
      this.previewImage = ''
      this.previewPicImage = ''
      this.logoList = []
      this.logoName = ''

      this.picList = []
    },
    add() {
      this.model = {}
      this.isEdit = false
      this.isAdd = true
      this.initUploadParams()
      this.selectSellerShow = true
      this.getShopTypeChange()
      this.visible = true
      this.logoName = ''

      this.form.resetFields()
    },
    edit(record) {
      this.visible = true
      this.isAdd = false
      this.isEdit = true
      this.selectSellerShow = false
      this.initUploadParams()
      this.getShopTypeChange()
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.$nextTick(() => {
        console.log(this.model)
        this.model.divideType = this.model.divideType == null ? '' : this.model.divideType.toString()
        this.model.divideNum = this.model.divideNum == null ? '' : this.model.divideNum.toString()
        this.model.workType = this.model.workType == null ? '' : this.model.workType.toString()
        this.form.setFieldsValue(
          pick(
            this.model,
            'shopName',
            'linkmanMobile',
            'shopType',
            'brief',
            'shopPhoto',
            'shopAddress',
            'logoList',
            'picUrls',
            'addressDetail',
            'coordinate',
            'workType',
            'divideType',
            'divideNum',
            'goodsTyeList'
          )
        )
        //console.log(this.model)
        // this.logoList.push[{ thumbUrl: this.model.logoPic,status:'done' ,type:'image/*' }]
        if (this.model.shopPhoto != null && this.model.shopPhoto != undefined) {
          let s = this.model.shopPhoto.split(',')
          for (let i in s) {
            console.log(s)
            this.picList[i] = {
              uid: Math.random(),
              name: s[i],
              url: this.imageDownloadUri + s[i],
              status: 'done',
              type: 'image/*'
            }
          }
        }
        if (this.model.logoPic != null && this.model.logoPic != undefined) {
          this.logoList.push({
            uid: Math.random(),
            name: this.model.logoPic,
            url: this.imageDownloadUri + this.model.logoPic,
            status: 'done',
            type: 'image/*'
          })
        }
        this.form.setFieldsValue({ sellerId: this.model.sellerId })
        // let file={url:this.DownLoadImage(this.model.logPic)}
        // this.handlePicPreview(file)
        //时间格式化
        this.isEdit = true
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    shouwList() {
      console.log(this.picList)
      console.log(this.logoList)
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          console.log(that.logoList)
          if (that.logoList == undefined || that.logoList.length == 0) {
            this.modalVisible = true
            that.modalText = '请上传至少一张店铺logo'

            that.confirmLoading = false

            return
          }
          if (that.picList.length < 1) {
            that.confirmLoading = false

            this.modalText = '请上传至少一张店铺照片'
            this.modalVisible = true

            return
          }

          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'post'
          }
          let formData = Object.assign(this.model, values)
          let picName = new Array()
          let pics = this.picList
          if (pics[0].response != undefined && pics[0].response != null) {
            for (let i in pics) {
              console.log(pics[i])
              if (pics[i].status == 'done' && pics[i].response.code != undefined && pics[i].response.code == 200) {
                console.log('=======' + pics[i].response.result.imageUri)
                picName[i] = pics[i].response.result.imageUri
              }
            }
            formData.shopPhoto = picName.join()
          }
          if (that.logoName.length > 0) {
            formData.logoPic = that.logoName
          }
          console.log(formData)
          httpAction(httpurl, formData, method)
            .then(res => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    handlePicCancel() {
      this.previewVisible = false
    },
    handlePicPreview(file) {
      if (this.isEdit) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      } else {
        this.previewPicImage = file.url || file.thumbUrl
        this.previewPicVisible = true
      }
    },
    handlePicChange({ fileList }) {
      this.picList = fileList
    },
    handleLogoCancel() {
      this.previewVisible = false
    },
    handleLogoPreview(file) {
      if (this.isEdit) {
        this.previewImage = file.thumbUrl
        this.previewVisible = true
      } else {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      }
    },
    handleLogoChange({ fileList }) {
      if (
        fileList.length > 0 &&
        fileList[0].status == 'done' &&
        fileList[0].response.code != undefined &&
        fileList[0].response.code == 200
      ) {
        this.logoName = fileList[0].response.result.imageUri
      }
      this.logoList = fileList
    },

    compress(img) {
      console.log(img)
      let canvas = document.createElement('canvas')
      let ctx = canvas.getContext('2d')
      let initSize = img.src.length
      let width = img.width
      let height = img.height
      canvas.width = width
      canvas.height = height
      // 铺底色
      ctx.fillStyle = '#fff'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      ctx.drawImage(img, 0, 0, width, height)

      //进行最小压缩
      let ndata = canvas.toDataURL('image/jpeg', 0.1)
      console.log('*******压缩后的图片大小*******')
      // console.log(ndata)
      console.log(ndata.length)
      return ndata
    },
    preprocessUploadImageFile(file, callback) {
      const self = this
      const ext = this.getExt(file.name)
      var reader = new FileReader()

      reader.onload = function(readerEvent) {
        var image = new Image()
        image.onload = function(imageEvent) {
          var canvas = document.createElement('canvas'),
            width = image.width,
            height = image.height,
            ratio = Math.sqrt(THUMB_IMAGE_TARGET_SIZE / file.size)
          width *= ratio
          height *= ratio
          canvas.width = width
          canvas.height = height
          canvas.getContext('2d').drawImage(image, 0, 0, width, height)
          var dataUrl = canvas.toDataURL('image/jpeg')
          var blobData = self.dataURItoBlob(dataUrl)
          callback(blobData)
        }
        image.src = readerEvent.target.result
      }
      reader.readAsDataURL(file)
    },
    resizeAndUploadImage(file) {
      return new Promise((ok, fail) => {
        console.log(file.size)
        if (file.size > IMAGE_TARGET_SIZE) return fail('圖片尺寸太大')
        if (!file.type.match(/image.*/)) return fail('file must be image')

        this.preprocessUploadImageFile(file, resizedImageBlob => {
          const ext = this.getExt(file.name)
          var nameObject = this.getRandomeFileNames(ext)
          this.uploadS3(nameObject.thumbname, resizedImageBlob)
            .then(data => {
              this.uploadS3(nameObject.name, file).then(data => {
                ok(nameObject.name, nameObject.thumbname)
              })
            })
            .catch(err => fail(err))
        })
      })
    },
    handleModalCancel() {},
    handleModalOk() {
      this.modalVisible = false
    }
  }
}
</script>

<style lang="less" scoped></style>
